<template>
    <div class="xiaoquan-tooltip" v-on="outerEvent">
        <div class="xiaoquan-tooltip__trigger" ref="triggerRef" v-on="events">
            <slot/>
        </div>
        <div class="xiaoquan-tooltip__popper" ref="poperRef" v-if="isOpen">
            <slot name="content">
                {{ content }}
            </slot>
            <div id="arrow" data-popper-arrow></div>
        </div>
    </div>
</template>

<script setup>
    import { createPopper } from '@popperjs/core';
    import { ref, watch, reactive, computed } from "vue";
    import propsObj from "./props";
    import { debounce } from "lodash-es";
    defineOptions({
        name: "XiaoQuan-Tooltip"
    });
    const emit = defineEmits(['visible-change'])
    const props = defineProps(propsObj);
    const triggerRef = ref(null); // 事件源对象
    const poperRef = ref(null); // 提示框元素
    let poperInstance = null;
    const isOpen = ref(false);
    const events = reactive({});
    const outerEvent = reactive({});

    const openDebounce = debounce(()=> {
        isOpen.value = true;
        emit('visible-change', true)
    }, props.openDelay)

    const closeDebounce =debounce(()=> {
        isOpen.value = false;
        emit('visible-change', false)
    }, props.closeDelay)

    const open = ()=> {
        closeDebounce.cancel();
        openDebounce();
    }
    const close = ()=> {
        openDebounce.cancel();
        closeDebounce();
    }
    const popperOptions = computed(()=> {
        return {
            placement: props.placement,
            modifiers: [
                {
                    name: 'offset',
                    options: {
                        offset: [0, 6],
                    },
                },
            ]
        }
    })

    watch(isOpen, (newVal)=> {
        if(newVal) {
            if(triggerRef.value && poperRef.value) {
                console.log(popperOptions)
                poperInstance = createPopper(triggerRef.value, poperRef.value, popperOptions.value);
            }
            return;
        }
        poperInstance?.destroy(); // 销毁提示框
    }, { flush: 'post' }) // post dom更新之后运行

    const attachEvent = ()=> { // 根据不同的触发方式 绑定不同的事件
        if(props.trigger === 'hover') {
            events['mouseenter'] = ()=> open();
            outerEvent['mouseleave'] = ()=> close();
        }else if(props.trigger === 'click') {
            events['click'] = ()=> isOpen.value ? close() : open();
        }
    }
    if(!props.manual) { // 如果不手动触发
        attachEvent();
    }

    defineExpose({
        show: open,
        hide: close
    })
</script>

<style scoped lang="scss">

</style>